<!DOCTYPE HTML>
<html lang="zh-CN">




<head>
    <meta charset="utf-8">
    <meta name="keywords" content="&#39;JavaNote04_Thread&#39;, 深度学习 故障诊断 Java">
    <meta name="description" content="河海大学 | 计算机与信息学院 | 信号与信息处理">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>&#39;JavaNote04_Thread&#39; | 世庆的博客</title>
    <link rel="icon" type="image/png" href="/shiqing/favicon.png">

    <link rel="stylesheet" type="text/css" href="/shiqing/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/shiqing/css/my.css">

    <script src="/shiqing/libs/jquery/jquery.min.js"></script>

    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 6.3.0"></head>




    <body>
        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/shiqing/" class="waves-effect waves-light">
                    
                    <img src="/shiqing/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">世庆的博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/shiqing/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/shiqing/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">世庆的博客</div>
        <div class="logo-desc">
            
            河海大学 | 计算机与信息学院 | 信号与信息处理
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/shiqing/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/sqtian-hhu/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/sqtian-hhu/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

        



<div class="bg-cover pd-header post-cover" style="background-image: url('/shiqing/medias/featureimages/3.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">&#39;JavaNote04_Thread&#39;</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/shiqing/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                                <span class="chip bg-color">Java基础</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/shiqing/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-18
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/shiqing/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="多线程"><a href="#多线程" class="headerlink" title="多线程"></a>多线程</h2><ol>
<li>并发与并行<br>并发：指两个或多个事件在同一时间段内发生<br>   交替执行,一个人吃两个馒头<br>并行：指两个或多个事件在同一时刻发生(同时发生)<br>   同时执行,两个人一人一个个馒头</li>
</ol>
<span id="more"></span>
<ol start="2">
<li>线程与进程<br>进程:一个内存中运行的应用程序</li>
</ol>
<p>硬盘:永久存储ROM<br>内存:所有应用程序都需要进入内存中执行,临时存储RAM<br>点击应用程序执行,进入到内存中占用一些内存执行,进入到内存的程序叫进程<br>结束进程,就把进程从内存中清除了</p>
<p>一个程序运行后至少有一个进程,一个进程可以包含多个线程<br>CPU:中央处理器,对数据进行计算,指挥电脑中的软件和硬件工作<br>4核8线程<br>8线程:同时执行8个任务<br>点击电脑管家运行,会进入到内存中,就是一个进程.点击功能(病毒查杀,清理垃圾,电脑加速)执行,<br>就会开启一条应用程序到cpu的执行路径,cpu就可以通过这个路径执行功能,这个路径就叫线程<br>线程属于进程,是进程中的一个执行单元,负责程序的执行</p>
<p>单核心单线程CPU:cpu在多个线程之间做高速的切换,轮流执行多个线程,效率低<br>4核心8线程:同时执行8个线程,8个线程在多个任务之间高速切换,效率提高了8倍</p>
<p>线程调度:<br>分时调度:所有线程轮流使用CPU,平均分配每个线程占用CPU的时间<br>抢占式调度:优先让优先级高的线程占用</p>
<ol start="3">
<li>创建线程类<br>主线程: 执行main方法的线程<br>单线程程序:Java程序中只有一个线程,执行从main开始,从上到下依次执行<br>public class Demo01MainThread {<br> public static void main(String[] args) {<br> Person p1 &#x3D; new Person(“小强”,10);<br> p1.run();&#x2F;&#x2F;单线程从上而下,p2全打印完了才继续运行p2,如果p1出现了异常,p2就运行不了了<br> Person p2 &#x3D; new Person(“旺财”,8);<br> p2.run();<br> }<br>}</li>
</ol>
<p>&#x2F;&#x2F;1.创建一个Thread类的子类<br>public class MyThread extends Thread {<br>    &#x2F;&#x2F;2. 在Thread类的子类中重写Thread类中的run方法,设置线程任务</p>
<pre><code>@Override
public void run() &#123;
    for (int i = 0; i &lt; 10000; i++) &#123;
        System.out.println(&quot;run:&quot; + i);
    &#125;
&#125;
</code></pre>
<p>}</p>
<p>&#x2F;*<br>    创建多线程程序的第一种方式:创建Thread类的子类<br>    实现步骤:<br>        1. 创建一个Thread类的子类<br>        2. 在Thread类的子类中重写Thread类的run方法,设置线程任务(开启线程要做什么)<br>        3. 创建Thread类的子类对象<br>        4. 调用Thread类中的方法start方法,开启新的线程,执行run方法<br>            void start() 使线程开始执行; Java 虚拟机调用该线程的run方法<br>            结果是两个线程并发的运行当前线程(main线程)和另一个线程(创建的新线程,执行其run方法)<br>            多次启动一个线程是非法的,特别是当线程已经结束执行后,不能再重新启动<br>        java程序属于抢占式调度,哪个线程优先级高,哪个线程优先执行,同一优先级随机选择一个执行</p>
<p> *&#x2F;<br>public class Demo01Thread {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;3. 创建Thread类子类对象<br>        MyThread mt &#x3D; new MyThread();<br>        &#x2F;&#x2F;4. 调用start<br>        mt.start();</p>
<pre><code>    //主线程
    for (int i = 0; i &lt; 10000; i++) &#123;
        System.out.println(&quot;main:&quot; + i);
    &#125;
&#125;
</code></pre>
<p>}</p>
<h2 id="多线程原理"><a href="#多线程原理" class="headerlink" title="多线程原理"></a>多线程原理</h2><p>JVM执行main方法,找OS开辟一条main方法通向cpu的路径,这个路径叫main线程,主线程<br>cpu通过这个线程,这个路径可以执行main方法</p>
<p>mythread.start() 执行run方法,开辟一条通向cpu的新路径,用来执行run方法<br>对于cpu而言,就有了两条执行的路径,cpu就有了选择的权力,cpu随机选择</p>
<p>start开辟新的栈空间,执行run方法,多个栈的线程互不影响</p>
<h2 id="Thread类的常用方法"><a href="#Thread类的常用方法" class="headerlink" title="Thread类的常用方法"></a>Thread类的常用方法</h2><p>获取线程名称：</p>
<ol>
<li>使用Thread类中的方法getName()<br> String getName() 返回该线程的名称</li>
<li>可以先获取到当前正在执行的线程,使用线程方法getName()获取当前线程名称<br> current Thread()</li>
</ol>
<p>设置线程名称:</p>
<ol>
<li>使用Thread类中的方法setName</li>
<li>创建一个带参数的构造方法,参数传递线程的名称;调用父类的带参构造,把线程名称传递给父类,让父类给子线程起一个名字</li>
</ol>
<p>&#x2F;&#x2F;1.创建一个Thread类的子类<br>public class MyThread extends Thread {<br>    &#x2F;&#x2F;2. 在Thread类的子类中重写Thread类中的run方法,设置线程任务</p>
<pre><code>public MyThread() &#123;
&#125;

public MyThread(String name) &#123;
    super(name);//
&#125;

@Override
public void run() &#123;
    //获取线程名称
</code></pre>
<p>&#x2F;&#x2F;		String name &#x3D; getName();<br>&#x2F;&#x2F;		System.out.println(name);&#x2F;&#x2F;Thread-0</p>
<h2 id="x2F-x2F-Thread-t-x3D-Thread-currentThread-x2F-x2F-System-out-println-t-x2F-x2F-Thread-Thread-0-5-main-x2F-x2F-String-name-x3D-t-getName-x2F-x2F-System-out-println-name-x2F-x2F-Thread-0-System-out-println-Thread-currentThread-getName"><a href="#x2F-x2F-Thread-t-x3D-Thread-currentThread-x2F-x2F-System-out-println-t-x2F-x2F-Thread-Thread-0-5-main-x2F-x2F-String-name-x3D-t-getName-x2F-x2F-System-out-println-name-x2F-x2F-Thread-0-System-out-println-Thread-currentThread-getName" class="headerlink" title="&#x2F;&#x2F;		Thread t &#x3D; Thread.currentThread();&#x2F;&#x2F;		System.out.println(t);&#x2F;&#x2F;Thread[Thread-0,5,main]&#x2F;&#x2F;		String name &#x3D; t.getName();&#x2F;&#x2F;		System.out.println(name);&#x2F;&#x2F;Thread-0        System.out.println(Thread.currentThread().getName());    }}"></a>&#x2F;&#x2F;		Thread t &#x3D; Thread.currentThread();<br>&#x2F;&#x2F;		System.out.println(t);&#x2F;&#x2F;Thread[Thread-0,5,main]<br>&#x2F;&#x2F;		String name &#x3D; t.getName();<br>&#x2F;&#x2F;		System.out.println(name);&#x2F;&#x2F;Thread-0<br>        System.out.println(Thread.currentThread().getName());<br><br>    }<br>}</h2><p>&#x2F;*<br>    线程的名称：<br>    主线程：main<br>    新线程：Thread-0，Thread-1…<br> *&#x2F;<br>public class Demo01GetThreadName {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;创建Thread子类对象<br>        MyThread mt &#x3D; new MyThread();<br>        &#x2F;&#x2F;1. 直接设置线程名称<br>        mt.setName(“CC”);<br>        mt.start();</p>
<pre><code>    //2. 父类构造方法设置名称
    new MyThread(&quot;TT&quot;).start();
&#125;
</code></pre>
<p>}</p>
<p>sleep方法<br>使当前正在执行的线程以指定的毫秒数暂停<br>毫秒数结束后,线程继续执行</p>
<p>public class Demo01Sleep {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;模拟秒表<br>        for (int i &#x3D; 0; i &lt; 60; i++) {<br>            System.out.println(i);<br>            &#x2F;&#x2F;使用Thread静态方法sleep睡眠一秒钟<br>            try {<br>                Thread.sleep(1000);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}</p>
<h2 id="创建多线程的另一种方式"><a href="#创建多线程的另一种方式" class="headerlink" title="创建多线程的另一种方式"></a>创建多线程的另一种方式</h2><p>实现Runnable接口<br>Runnable接口应该由那些打算通过某一线程执行其实例的类来实现,类必须定义一个称为run的无参方法<br>实现步骤:</p>
<ol>
<li>创建一个Runnable接口的实现类</li>
<li>在实现类中重写Runnable接口的run方法,设置线程任务</li>
<li>创建一个Runnable接口的实现类对象</li>
<li>创建Thread类的对象,构造方法中传递Runnable接口的实现类对象</li>
<li>调用Thread类中的方法start方法,开启新的线程</li>
</ol>
<p>public class RunnableImpl implements Runnable{</p>
<pre><code>@Override
public void run() &#123;
    for (int i = 0; i &lt; 20; i++) &#123;
        System.out.println(Thread.currentThread().getName()+&quot;--&gt;&quot;+i);
    &#125;
&#125;
</code></pre>
<h2 id=""><a href="#" class="headerlink" title="}"></a>}</h2><p>public class Demo01Runnable {<br>    public static void main(String[] args) {<br>        RunnableImpl run &#x3D; new RunnableImpl();<br>        Thread t &#x3D; new Thread(run);<br>        t.start();<br>        for (int i &#x3D; 0; i &lt; 20; i++) {<br>            System.out.println(Thread.currentThread().getName()+”–&gt;”+i);<br>        }<br>    }<br>}</p>
<h2 id="Thread和Runnable的区别"><a href="#Thread和Runnable的区别" class="headerlink" title="Thread和Runnable的区别"></a>Thread和Runnable的区别</h2><p>实现Runnable接口创建多线程的好处:<br>    1. 避免了单继承的局限性<br>        一个类只能继承一个类,类继承了Thread类就不能继承其他的类了<br>        实现Runnable接口,还可以继承其他的类,实现其他接口<br>    2. 增强了程序的扩展性,降低了程序的耦合性<br>        实现Runnable接口的方式,把设置线程任务和开启新线程进行了分离<br>        实现类中,重写了run方法:用来设置线程任务<br>        创建Thread类对象,调用start方法:用来开启新线程<br>        Thread t &#x3D; new Thread(run);分离后可以传递不同的Runnable接口的实现类对象</p>
<p>尽量通过Runnable接口的形式</p>
<h2 id="匿名内部类的方式创建"><a href="#匿名内部类的方式创建" class="headerlink" title="匿名内部类的方式创建"></a>匿名内部类的方式创建</h2><p>把子类继承父类,重写父类方法,创建子类对象合一步完成<br>把实现类实现接口,重写接口中的方法,创建实现类对象合成一步完成</p>
<p>匿名内部类最终产物:子类对象&#x2F;实现类对象,而这个类没有名字</p>
<p>格式:<br>    new 父类&#x2F;接口(){<br>        重写方法<br>    };</p>
<p>public class Demo01InnerClassThread {<br>    public static void main(String[] args){<br>        &#x2F;&#x2F;线程的父类是Thread<br>        &#x2F;&#x2F; new MyThread().start();</p>
<pre><code>    //匿名内部类
    new Thread()&#123;
        @Override
        public void run() &#123;
            for (int i = 0; i &lt; 20; i++) &#123;
                System.out.println(Thread.currentThread().getName()+&quot;--&gt;&quot;+i+&quot;TT&quot;);
            &#125;
        &#125;
    &#125;.start();

    //接口方式
    //Runnable r = new RunnableImpl();//多态

    //匿名内部类
    Runnable r = new Runnable()&#123;

        @Override
        public void run() &#123;
            for (int i = 0; i &lt; 20; i++) &#123;
                System.out.println(Thread.currentThread().getName()+&quot;--&gt;&quot;+i+&quot;CC&quot;);
            &#125;
        &#125;
    &#125;;

    new Thread(r).start();

    new Thread(new Runnable()&#123;

        @Override
        public void run() &#123;
            for (int i = 0; i &lt; 20; i++) &#123;
                System.out.println(Thread.currentThread().getName()+&quot;--&gt;&quot;+i+&quot;AB&quot;);
            &#125;
        &#125;
    &#125;).start();
&#125;
</code></pre>
<p>}</p>
<h2 id="线程安全问题"><a href="#线程安全问题" class="headerlink" title="线程安全问题"></a>线程安全问题</h2><p>卖票案例:</p>
<ol>
<li>只有一个窗口卖1-100号票,单线程,线程安全</li>
<li>三个窗口,分别卖1-33,34-66,67-100,多线程程序,没有访问共享数据,也不会出现问题</li>
<li>三个窗口,都在卖1-100号,多线程访问了共享数据,就会出现线程安全问题</li>
</ol>
<p>public class RunnableImpl implements Runnable{<br>&#x2F;*<br>     实现卖票案例</p>
<p> *&#x2F;</p>
<pre><code>//定义一个多线程共享的票源
private int ticket = 100;
//设置线程任务:卖票

@Override
public void run() &#123;
    //使用循环,让卖票重复进行
    while(ticket&gt;0)&#123;
        //票存在,卖票
        System.out.println(Thread.currentThread().getName()+&quot;正在卖第&quot;+ ticket +&quot;张票&quot;);
        ticket--;
    &#125;
&#125;
</code></pre>
<h2 id="-1"><a href="#-1" class="headerlink" title="}"></a>}</h2><p>&#x2F;*<br>    模拟卖票<br>    创建3个线程,同时开启,对共享的票进行出售<br> *&#x2F;</p>
<p>public class Demo01Ticket {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;创建Runnable接口的实现类对象<br>        RunnableImpl run &#x3D; new RunnableImpl();<br>        Thread t1 &#x3D; new Thread(run);<br>        Thread t2 &#x3D; new Thread(run);<br>        Thread t3 &#x3D; new Thread(run);<br>        t1.start();<br>        t2.start();<br>        t3.start();<br>    }<br>}</p>
<h2 id="解决线程安全问题"><a href="#解决线程安全问题" class="headerlink" title="解决线程安全问题"></a>解决线程安全问题</h2><p>运用同步机制<br>!. 同步代码块<br>2. 同步方法<br>3. 锁机制</p>
<ol>
<li>同步代码块<br>public class RunnableImpl implements Runnable{<br>&#x2F;*<br>  实现卖票案例<br>  出现了线程安全问题<br>  卖出了不存在的票和重复的票<br>  使用同步代码块解决<br>  格式:<br>  synchronized(锁对象){<br>      可能会出现线程安全问题的代码块<br>  }<br>  注意:<br>  1. 通过代码块中的锁对象,可以使用任意的对象<br>  2. 但是必须保证多个线程使用的锁对象是同一个<br>  3. 锁对象作用:把同步代码块锁住,只让一个线程在同步代码块中执行</li>
</ol>
<p> *&#x2F;</p>
<pre><code>//定义一个多线程共享的票源
private int ticket = 100;
//设置线程任务:卖票

//创建一个锁对象
Object obj = new Object();

@Override
public void run() &#123;
    //使用循环,让卖票重复进行
    while(true)&#123;
        synchronized(obj)&#123;
            if(ticket &gt; 0)&#123;
                //票存在,卖票
                System.out.println(Thread.currentThread().getName()+&quot;正在卖第&quot;+ ticket +&quot;张票&quot;);
                ticket--;
            &#125;

        &#125;
    &#125;
&#125;
</code></pre>
<hr>
<p>同步技术的原理:<br>使用了一个锁对象,这个锁对象叫做同步锁,也叫对象锁,也叫对象监视器<br>3个线程一起抢夺cpu执行权,谁抢到了谁执行run方法进行卖票,<br>t0抢到了执行权,执行run方法,遇到synchronized代码块,<br>这是t0会检查synchronized代码块是否有锁对象,<br>发现有,就会获取到锁对象,进入到同步中执行<br>t1抢到了cpu的执行权,遇到synchronized代码块,<br>这是t1检查锁对象,发现没有,t1就会进入阻塞状态,会一直等待t0归还锁对象<br>t0执行完同步代码块中的代码,才会归还锁对象</p>
<ol start="2">
<li>同步方法解决<br>使用步骤:</li>
<li>把访问了共享数据的代码抽取出来,放到一个方法中</li>
<li>在方法上添加synchronized修饰符</li>
</ol>
<p>格式: 定义方法的格式<br>修饰符 synchronized 返回值类型 方法名(参数列表){<br>    可能出现线程安全问题的代码(共享数据的代码)<br>}</p>
<p>@Override<br>    public void run() {<br>        payTicket();<br>    }</p>
<pre><code>/*
    定义一个同步方法
    同步方法也会把方法内部的代码锁住
    只让一个线程执行
    同步方法的锁对象就是实现类对象 new RunnableImpl()
    也就是this
 */
public synchronized void payTicket()&#123;
    //使用循环,让卖票重复进行
    while(ticket &gt; 0)&#123;
        synchronized(obj)&#123;
            //票存在,卖票
            System.out.println(Thread.currentThread().getName()+&quot;正在卖第&quot;+ ticket +&quot;张票&quot;);
            ticket--;
        &#125;
    &#125;
&#125;
</code></pre>
<p>静态同步方法</p>
<p>public class RunnableImpl implements Runnable{<br>    &#x2F;&#x2F;静态访问静态<br>    private static int ticket &#x3D; 100;<br>    &#x2F;&#x2F;设置线程任务:卖票</p>
<pre><code>@Override
public void run() &#123;
    payTicket();
&#125;
public static synchronized void payTicket()&#123;
    //使用循环,让卖票重复进行
    while(ticket &gt; 0)&#123;
        synchronized(obj)&#123;
            //票存在,卖票
            System.out.println(Thread.currentThread().getName()+&quot;正在卖第&quot;+ ticket +&quot;张票&quot;);
            ticket--;
        &#125;
    &#125;
&#125;
</code></pre>
<p>静态方法的锁对象不能是this，this是创建对象后产生的，静态方法优先于对象<br>静态方法的锁对象是本类的class属性 –&gt; class文件对象 RunnableImpl.class</p>
<ol start="3">
<li><p>Lock锁<br>Lock接口可获得更广泛的锁定结构<br>lock获取锁<br>unlock释放锁<br> &#x2F;*<br>     第三种方案:Lock锁<br>     ReentrantLock implements Lock 接口<br>     使用步骤:<br>         1. 在成员位置创建一个ReentrantLock对象<br>         2. 在可能出现安全问题的代码前调用Lock接口中的lock方法获取锁<br>         3. 在可能出现安全问题的代码后调用Lock接口中的unlock方法释放锁<br><br>  *&#x2F;<br> Lock l &#x3D; new Reentrant Lock();</p>
<p> @Override<br> public void run() {<br> &#x2F;&#x2F;使用循环,让卖票重复进行<br> l.lock();<br> while(ticket &gt; 0){<br>     synchronized(obj){<br>             &#x2F;&#x2F;票存在,卖票<br>             System.out.println(Thread.currentThread().getName()+”正在卖第”+ ticket +”张票”);<br>             ticket–;<br>     }<br> }<br> l.unlock();<br> }</p>
</li>
</ol>
<p>如果try…catch异常,把unlock放在finally语句里,无论程序是否异常,都会把锁释放<br>    @Override<br>    public void run() {<br>        &#x2F;&#x2F;使用循环,让卖票重复进行<br>        l.lock();<br>        while(ticket &gt; 0){</p>
<pre><code>        try &#123;
            Thread.sleep(1000);
            //票存在,卖票
                System.out.println(Thread.currentThread().getName()+&quot;正在卖第&quot;+ ticket +&quot;张票&quot;);
                ticket--;
        &#125; catch (InterruptedException e) &#123;
            e.printStackTrace();
        &#125;finally&#123;
            l.unlock();
        &#125;	
    &#125;
&#125;
</code></pre>
<h2 id="线程状态"><a href="#线程状态" class="headerlink" title="线程状态"></a>线程状态</h2><p>NEW 新建状态<br>BLOCKED 阻塞状态  RUNNABLE 运行状态<br>TIMED_WAITING 休眠状态  WAITING 无限等待状态<br>TERMINATED 死亡状态</p>
<p>TIMED_WAITING 休眠状态  sleep<br>BLOCKED 阻塞状态    lock</p>
<p>WAITING 无限等待状态<br>一个正在无限等待另一个线程执行一个特别的唤醒动作的线程处于这一状态<br>卖包子案例：<br>顾客要买包子，和老板说明买包子的数量和种类，顾客就等着老板做包子(调用wait方法) Waiting状态 无限等待</p>
<p>老板开始做包子,做好包子告诉顾客(调用notify方法)</p>
<p>&#x2F;*<br>    等待唤醒案例：线程之间的通信<br>        创建一个顾客线程（消费者）：告知老板要的包子种类和数量，调用wait，放弃cpu执行，进入无限等待<br>        创建一个老板线程（生产者）：花了5秒做包子，做好包子后调用notify唤醒顾客<br>    注意：<br>        顾客和老板线程必须使用同步代码包裹起来，保证等待和唤醒只能有一个执行<br>        同步使用的锁对象必须保证唯一<br>        只有锁对象才能调用wait和notify方法<br>    Object类中的方法<br>    void wait()<br>        在其他线程调用此对象的notify()方法或notifyAll()方法前,导致当前线程等待<br>    void notify()<br>        唤醒在此对象监视器上等待的单个线程<br>        会继续执行wait方法之后的代码</p>
<p> *&#x2F;<br>public class Demo01WaitAndNotify {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;创建锁对象保证唯一<br>        Object obj &#x3D; new Object();<br>        &#x2F;&#x2F;创建一个顾客线程<br>        new Thread(){<br>            @Override<br>            public void run() {<br>                &#x2F;&#x2F;保证等待和唤醒的线程只能有一个执行,需要使用同步技术<br>                synchronized (obj){<br>                    System.out.println(“告知老板包子的种类和数量”);<br>                    &#x2F;&#x2F;调用wait方法<br>                    try {<br>                        obj.wait();<br>                    } catch (InterruptedException e) {<br>                        e.printStackTrace();<br>                    }<br>                    &#x2F;&#x2F;唤醒之后执行的代码<br>                    System.out.println(“包子做好了,真香”);<br>                }<br>            }<br>        }.start();</p>
<pre><code>    //创建一个老板线程
    new Thread()&#123;
        @Override
        public void run() &#123;
            //花了五秒做包子
            try &#123;
                Thread.sleep(5000);
            &#125; catch (InterruptedException e) &#123;
                e.printStackTrace();
            &#125;

            //保证等待和唤醒的线程只能有一个执行,需要使用同步技术
            synchronized (obj)&#123;
                //调用notify唤醒顾客
                System.out.println(&quot;唤醒顾客&quot;);
                obj.notify();
            &#125;
        &#125;
    &#125;.start();
&#125;
</code></pre>
<p>}</p>
<p>进入TimeWaiting有两种方式<br>    1. 使用sleep(Long m)方法,计时结束后自动进入Runnable&#x2F;Blocked状态<br>    2. 使用wait(Long m)方法,毫秒结束后如果还没有被唤醒,自动进入Runnable&#x2F;Blocked状态</p>
<p>唤醒的方法:<br>    notify() 唤醒单个线程,如果有多个,随机唤醒一个<br>    notifyAll() 唤醒监视器上等待的所有线程</p>
<h2 id="等待唤醒机制"><a href="#等待唤醒机制" class="headerlink" title="等待唤醒机制"></a>等待唤醒机制</h2><p>线程间通信<br>多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同<br>比如:线程A生产包子,线程B吃包子,包子是同一资源,但是线程A线程B处理的动作不同,就存在线程通信问题</p>
<p>包子案例实现:</p>
<h2 id="public-class-BaoZi-x2F-x2F-皮-String-pi-x2F-x2F-馅-String-xian-x2F-x2F-包子的状态-boolean-flag-x3D-false"><a href="#public-class-BaoZi-x2F-x2F-皮-String-pi-x2F-x2F-馅-String-xian-x2F-x2F-包子的状态-boolean-flag-x3D-false" class="headerlink" title="public class BaoZi {    &#x2F;&#x2F;皮    String pi;    &#x2F;&#x2F;馅    String xian;    &#x2F;&#x2F;包子的状态    boolean flag &#x3D; false;}"></a>public class BaoZi {<br>    &#x2F;&#x2F;皮<br>    String pi;<br>    &#x2F;&#x2F;馅<br>    String xian;<br>    &#x2F;&#x2F;包子的状态<br>    boolean flag &#x3D; false;<br>}</h2><p>&#x2F;*<br>    包子铺线程和顾客线程关系–&gt;通信(互斥)<br>    必须使用同步技术保证两个线程只有一个执行<br>    锁对象必须保证唯一,可以使用包子对象作为锁对象<br>    包子铺类和顾客类就需要把包子对象作为参数传递进来<br>        1. 需要在成员位置创建一个包子变量<br>        2. 使用带参数构造方法,为包子变量赋值<br> *&#x2F;<br>public class BaoZiPu extends Thread{<br>    private BaoZi bz;</p>
<pre><code>public BaoZiPu(BaoZi bz) &#123;
    this.bz = bz;
&#125;

//设置线程生产包子
@Override
public void run() &#123;
    int count = 0;
    //让包子一直生产到100个包子
    while(count&lt;100)&#123;
        //同步技术
        synchronized (bz)&#123;
            if(bz.flag == true)&#123;
                //包子铺调用wait方法进入等待状态
                try &#123;
                    bz.wait();
                &#125; catch (InterruptedException e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            //被唤醒后生产包子
            //交替生产两种包子
            if(count%2 == 0)&#123;
                //生产薄皮三鲜馅儿
                bz.pi = &quot;薄皮&quot;;
                bz.xian = &quot;三鲜馅儿&quot;;
            &#125;else&#123;
                //生产冰皮牛肉大葱馅儿
                bz.pi = &quot;冰皮&quot;;
                bz.xian = &quot;牛肉大葱馅儿&quot;;
            &#125;
            count++;

            System.out.println(&quot;包子铺正在做&quot;+bz.pi+bz.xian+&quot;的包子&quot;);
            //做一个包子五秒钟
            try &#123;
                Thread.sleep(5000);
            &#125; catch (InterruptedException e) &#123;
                e.printStackTrace();
            &#125;
            //做好包子,flag改成有
            bz.flag = true;
            bz.notify();
            System.out.println(&quot;包子铺做好了&quot;+bz.pi+bz.xian+&quot;的包子&quot;);
    &#125;

    &#125;
&#125;
</code></pre>
<p>}</p>
<hr>
<p>public class ChiHuo extends Thread {<br>    private BaoZi bz;</p>
<pre><code>public ChiHuo(BaoZi bz) &#123;
    this.bz = bz;
&#125;

@Override
public void run() &#123;
    int count=0;
    while(count&lt;100)&#123;
        synchronized (bz)&#123;
            if(bz.flag == false)&#123;
                try &#123;
                    bz.wait();
                &#125; catch (InterruptedException e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;

            //被唤醒后吃包子
            System.out.println(&quot;顾客在吃&quot;+bz.pi+bz.xian+&quot;的包子&quot;);
            try &#123;
                Thread.sleep(3000);
            &#125; catch (InterruptedException e) &#123;
                e.printStackTrace();
            &#125;
            //吃完包子修改状态为没有
            bz.flag = false;
            count++;
            //唤醒包子铺继续生产
            bz.notify();
            System.out.println(&quot;顾客把&quot;+bz.pi+bz.xian+&quot;的包子吃完了&quot;);
            System.out.println(&quot;--------------------------------------&quot;);
        &#125;
    &#125;
&#125;
</code></pre>
<p>}</p>
<hr>
<p>public class Demo {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;创建包子对象<br>        BaoZi bz &#x3D; new BaoZi();<br>        &#x2F;&#x2F;创建包子铺线程,开始生产包子<br>        new BaoZiPu(bz).start();<br>        &#x2F;&#x2F;创建顾客线程,开始吃包子<br>        new ChiHuo(bz).start();<br>    }<br>}</p>
<h2 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h2><p>我们使用线程的时候就去创建一个线程，这样实现起来非常简便，但是存在一个问题：<br>如果并发线程数量很多，并且每一个线程都执行一个时间很短的任务就结束了，<br>这样频繁创建线程会大大降低系统的效率，<br>需要一种办法使线程可以复用，执行完一个任务，并不被销毁，而是可以继续执行其他的任务</p>
<p>线程池：一个容器–&gt;集合(ArrayList,HashSet,LinkedList<Thread>,HashMap)</p>
<p>当程序第一次启动的时候,创建多个线程,保存到一个集合中,<br>当我们想要使用线程的时候,就可以从集合中取出来线程使用<br>Thread t &#x3D; list.remove(0):返回的使被移除的元素,线程只能被一个任务使用<br>或者 Thread t &#x3D; linked.removeFirst();<br>当我们使用完毕线程,需要把线程归还给线程池<br>list.add(t);<br>或者linked.addLast(t);</p>
<p>JDK1.5之后,JDK内置了线程池,可以直接使用</p>
<p>&#x2F;&#x2F;2. 创建一个类,实现Runnable接口,重写run方法,设置线程任务<br>public class RunnableImpl2 implements Runnable{</p>
<pre><code>@Override
public void run() &#123;
    System.out.println(Thread.currentThread().getName()+&quot;创建一个新的线程执行&quot;);
&#125;
</code></pre>
<h2 id="-2"><a href="#-2" class="headerlink" title="}"></a>}</h2><p>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;</p>
<p>&#x2F;*<br>    java.util.concurrent.Executor: 线程池的工厂类,用来生成线程池<br>    Executors类中的方法:<br>        static ExecutorService newFixed Thread Pool(int nThreads) 创建一个可重用固定线程数的线程池<br>        参数:<br>            int nThreads:创建线程池中包含的线程数量<br>            返回值:<br>                ExecutorService接口,返回的是ExecutorService接口的实现类对象,我们可以使用ExecutorService接口接收(面向接口编程)<br>    java.util.concurrent.ExecutorService:线程池接口<br>        用来从线程池中获取线程,调用start方法执行线程任务<br>            submit(Runnable task)提交一个 Runnable 任务用于执行<br>        关闭线程池的方法: void shutdown()<br>    线程池的使用步骤:<br>        1. 使用线程的工厂类Executors里提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池<br>        2. 创建一个类,实现Runnable接口,重写run方法,设置线程任务<br>        3. 调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法<br>        4. 调用ExecutorService中的方法shutdown销毁线程池(不建议执行)</p>
<p> *&#x2F;<br>public class Demo01ThreadPool {<br>    public static void main(String[] args) {<br>        &#x2F;&#x2F;1. 使用线程的工厂类Executors里提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池<br>        ExecutorService es &#x3D; Executors.newFixedThreadPool(2);<br>        &#x2F;&#x2F;3. 调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法<br>        es.submit(new RunnableImpl2());&#x2F;&#x2F;pool-1-thread-1创建一个新的线程执行<br>        es.submit(new RunnableImpl2());&#x2F;&#x2F;pool-1-thread-2创建一个新的线程执行<br>        es.submit(new RunnableImpl2());&#x2F;&#x2F;pool-1-thread-1创建一个新的线程执行<br>        es.shutdown();<br>    }<br>}</p>
<hr>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/shiqing/about" rel="external nofollow noreferrer">ShiQing</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shiqing.gitee.io/shiqing/2020/03/18/java-ji-chu/javanote04-thread/">https://shiqing.gitee.io/shiqing/2020/03/18/java-ji-chu/javanote04-thread/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/shiqing/about" target="_blank">ShiQing</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                                    <span class="chip bg-color">Java基础</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/shiqing/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/shiqing/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/shiqing/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/shiqing/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/shiqing/2020/03/19/java-ji-chu/javanote05-lambda/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/15.jpg" class="responsive-img" alt="&#39;JavaNote05_Lambda&#39;">
                        
                        <span class="card-title">&#39;JavaNote05_Lambda&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Lambda表达式3.1 函数式编程思想概述尽量忽略面向对象的复杂语法，强调做什么，而不是以什么形式做
面向对象的思想：做一件事情，找一个能解决这个事情的对象，调用对象的方法，完成事情函数式编程思想：只要能获取到结果，怎么做的都不重要，重视
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                        <span class="chip bg-color">Java基础</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/shiqing/2020/03/16/java-ji-chu/javanote03-exception/">
                    <div class="card-image">
                        
                        
                        <img src="/shiqing/medias/featureimages/9.jpg" class="responsive-img" alt="&#39;JavaNote03_Exception&#39;">
                        
                        <span class="card-title">&#39;JavaNote03_Exception&#39;</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            异常指执行过程出现非正常情况,Java处理异常的方式是中断处理Throwable 异常的根类Error: extends Throwable,不能处理只能尽量避免Exception: extends Throwable,由于使用不当导致,可
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-16
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/shiqing/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/shiqing/tags/Java%E5%9F%BA%E7%A1%80/">
                        <span class="chip bg-color">Java基础</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/shiqing/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/shiqing/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/shiqing/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




        <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/shiqing/about" target="_blank">ShiQing</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2528393970@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2528393970" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2528393970" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/shiqing/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/shiqing/search.xml', 'searchInput', 'searchResult');
});
</script>

        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


        <script src="/shiqing/libs/materialize/materialize.min.js"></script>
        <script src="/shiqing/libs/masonry/masonry.pkgd.min.js"></script>
        <script src="/shiqing/libs/aos/aos.js"></script>
        <script src="/shiqing/libs/scrollprogress/scrollProgress.min.js"></script>
        <script src="/shiqing/libs/lightGallery/js/lightgallery-all.min.js"></script>
        <script src="/shiqing/js/matery.js"></script>

        <!-- Baidu Analytics -->

        <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

        
        <script src="/shiqing/libs/others/clicklove.js" async="async"></script>
        
        
        <script async src="/shiqing/libs/others/busuanzi.pure.mini.js"></script>
        

        <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我~看不见我~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script>

        <!-- 背景樱花飘落特效 -->
        
            <script type="text/javascript">
                //只在桌面版网页启用特效
                var windowWidth = $(window).width();
                if (windowWidth > 768) {
                    document.write('<script type="text/javascript" src="/js/xuehuapiaoluo.js"><\/script>');
                }
            </script>
        

        

        


        
        

        

        

        
        <script src="/shiqing/libs/instantpage/instantpage.js" type="module"></script>
        

    </body>

</html>
